<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box {
            width: 500px;
            margin: 0 auto;
        }
        
        h2 {
            /* display: inline-block; */
            width: 100px;
            float: left;
        }
        
        span {
            display: block;
            width: 45px;
            float: right;
            margin-top: 25px;
        }
        
        header::after {
            content: "";
            display: block;
            clear: both;
        }
        
        .box1::after {
            content: "";
            display: block;
            clear: both;
        }
        
        input {
            float: left;
        }
        
        button {
            float: right;
        }
        
        ul li {
            float: left;
            margin-right: 20px;
        }
    </style>
</head>

<body>
    <div class="box">
        <header>
            <input type="text">
            <button>搜索</button>
        </header>
        <div class="box1">
            <h2>搜索记录</h2>
            <span>清空</span>
        </div>
        <ul></ul>
    </div>
    <script>
        let inp = document.querySelector("input")
        let btn = document.querySelector("button")
        let span = document.querySelector("span")
        let ul = document.querySelector("ul")
        let arr = []
        let a = JSON.parse(localStorage.getItem("arr"))
        if (a !== null) {
            ran()
        }
        btn.addEventListener("click", function() {
            // arr.unshift(inp.value)
            // localStorage.setItem("arr", JSON.stringify(arr))

            if (a !== null) {

                let arr = a
                arr.unshift(inp.value)
                localStorage.setItem("arr", JSON.stringify(arr))
                ran()
            } else {
                let arr = []
                arr.unshift(inp.value)
                localStorage.setItem("arr", JSON.stringify(arr))
                ran()
            }


        })

        function ran() {

            let str = ""

            let data = JSON.parse(localStorage.getItem("arr"))

            data.forEach(function(v) {

                str += `<li>${v}</li>`

                ul.innerHTML = str
            })
        }
        span.addEventListener("click", function() {
            localStorage.clear()
            ul.textContent = ""

        })
    </script>
</body>

</html>